<?php

/**
 * Created by PhpStorm.
 * User: 子不语
 * Date: 2016/7/8
 * Time: 12:27
 */
class GameAction extends GamebaseAction
{
    function __construct()
    {
        parent::__construct();
    }
    function index(){
        $id=Req::get('id','intval');
        $this->assign('id',$id);
        $this->display('game_index');
    }
    function game(){
        $id=Req::get('id');
        $this->assign('id',$id);
        $games=$this->GetGameConfig($id);
        $sql='select game_std_odds,game_std_press from game_config where game_type='.$id;
        $press=db::get_one($sql);
        $this->assign('press',explode(',',$press->game_std_press));//标准投注额
        $step = $this->GetFromBeginNumStep($id);
        $this->assign('step',$step);//步进
        $this->assign('game_name',$games['game_name']);

        $this->assign('pl',$this->get_config($id));

        if($id==16){
            $in='n';
        }elseif(in_array($id,[11,12,13,21])){
            $in='3';
        }
        $this->assign('in',$in);
        if(in_array($id,[11,12,13,21,16])){
            $this->assign('odds',explode('|',$press->game_std_odds));
            return $this->display('game_36');
        }else {
            return $this->display('game');
        }
    }
    function press(){
        $no=Req::get('no','intval');
        $id=Req::get('id','intval');
        $this->assign('id',$id);
        $LastNo=$no-1;
        $arrCurNoInfo = array('preno'=>'','prekgtime'=>'','game_kj_delay'=>'','game_tz_close'=>'');
        $this->GetHeadContent($id,$sid=1,$arrCurNoInfo);
        //var_dump($head);
        /*$kjSec = $arrCurNoInfo['prekgtime'] + $arrCurNoInfo['game_kj_delay'];
        $StopSec = $arrCurNoInfo['prekgtime'] - $arrCurNoInfo['game_tz_close'];
        $this->assign('kjSec',$kjSec);
        $this->assign('StopSec',$StopSec);
        $this->assign('last_lotto',$head['last_lotto']);*/

        $result=$this->GetOdds($id, $no, $LastNo);
        $this->assign('pl',$this->get_config($id));
        $this->assign('no',$no);
        $this->assign('tzpoints',array_sum($result['press']));//已下注金豆
        $this->assign('list',$result);
        $games=$this->GetGameConfig($id);
        $this->assign('game_name',$games['game_name']);
        $info=$this->RefreshPoints();
        $this->assign('money',$info);
        return $this->display('game_press');
    }
    function ajax(){
        $id=Req::get('id','intval');
        $arrCurNoInfo = array('preno'=>'','prekgtime'=>'','game_kj_delay'=>'','game_tz_close'=>'');
        $arrCurNoInfo=$this->GetKjTzTime($id);
        $data=$this->GetTableContent($id,1 ,20 , $arrCurNoInfo);
        $info=$this->RefreshPoints();
        $data['points']=$this->info['points'];
        $data['bank']=$this->info['bankpoints'];

        if(in_array($id,array(11,12,13,21))){
            $data['type']='3';
        }elseif($id==16){
            $data['type']='n';
        }else{
            $data['type']='';
        }

        echo json_encode($data,JSON_UNESCAPED_UNICODE);
    }
    function AjaxCurrNo(){
        $no=Req::get('no','intval');
        $id=Req::get('id','intval');
        $currNo=$this->GetCurrNo($id,$no);
        
        echo json_encode($currNo,JSON_UNESCAPED_UNICODE);
    }
    function PostPress(){
        $No=Req::post('no','intval');
        $press=Req::post('press');
        $GameType=Req::post('gtype','intval');
        $Press=explode(',',$press);


        $arrRet = array('cmd'=>'ok','msg'=>'');
        $procedue = "";
        //判断投注串合法性
        if(!$this->CheckPressStrValid($GameType,$Press)) {
            return $this->result(1,'投注验证失败!');
        }
        //判断下注间隔时间
        if(isset($_SESSION["pressinterval"]) && isset($_SESSION["lastpresstime"])) {
                if( strtotime(date('Y-m-d H:i:s',time())) - $_SESSION["lastpresstime"] <= $_SESSION["pressinterval"] ) {
                    return $this->result(1,'下注太频繁了!');
                }
        }else{
            $sql = "select fldValue from sys_config where fldVar in('game_press_interval')";
            $result=db::get_one($sql,'assoc');
            $_SESSION["pressinterval"] = $result["fldValue"];
        }

        //判断游戏是否允许下注
        $sql = "select fldVar,fldValue from sys_config where fldVar in('game_open_flag','game_shutdown_reason') order by fldIdx";
        $result=db::get_one($sql,'assoc');
            if($result["fldValue"] == "1"){
                return $this->result(1,"游戏已停止下注,原因:" . $result["fldValue"]);
            }

        //判断单个游戏是否允许下注
        $sql = "select isstop,stop_msg from game_config where game_type = '{$GameType}'";
        $result=db::get_one($sql,'assoc');
            if($result["isstop"] == 1){
                return $this->result(1,'游戏已停止下注,原因:'.$result['stop_msg']);
            }
        //判断用户
        $sql = "select dj,isagent from users where id = '{$_SESSION['usersid']}'";
        $result=db::get_one($sql,'assoc');
        if($result["isagent"] == 1){
            return $this->result(1,'为了安全，代理绑定帐号禁止玩游戏');
        }
        if($result["dj"] == 1){
            return $this->result(1,'帐号已被冻结');
        }

        if($this->CheckAutoPress($GameType)){
            return $this->result(1,'您已经设置了自动投注！请先取消');
        }
        $step = $this->GetFromBeginNumStep($GameType);
        $procedue = "web_tz_" . $this->GetGameTableName($GameType,"game");

        if($procedue == "web_tz_"){
            return $this->result(1,'游戏类型错误!');
        }
        $sumScore = 0;
        $arrPress = $Press;

        $PressStr = "";
        for($i = 0 ; $i < count($arrPress); $i++)
        {
            if($arrPress[$i] != "" && intval($arrPress[$i]) > 0)
            {
                //$arrPress[$i]*=1000;
                $PressStr .= ($i+$step) . "," . $arrPress[$i] . "|";
                $sumScore += intval($arrPress[$i]);
            }
        }
        if($PressStr == ""){
            return $this->result(1,'您还没有投注!');
        }
        $PressStr = substr($PressStr,0,-1);

        if($this->CheckGameTimeout($GameType,$No)){
            return $this->result(1,'本期投注时间已过，请选其它期!');
        }
        //保存
        $sql = "call {$procedue}({$_SESSION['usersid']},{$No},{$sumScore},0,'{$PressStr}')";
        $arr = db::get_all($sql,'assoc');
        switch($arr[0]["result"])
        {
            case '0': //成功
                $_SESSION["points"] = $arr[0]["points"];
                $_SESSION["bankpoints"] = $arr[0]["back"];
                $_SESSION["lastpresstime"] = strtotime(date('Y-m-d H:i:s',time()));
                $arrRet['cmd'] = "0";
                $arrRet['msg'] = number_format($arr[0]["points"]) . "|" . number_format($arr[0]["points"]);
                break;
            case '1': //投注额过小
                $arrRet['cmd'] = "1";
                $arrRet['msg'] = "您的投注额小于最小限制" . $web_presspoint_game28_min;
                break;
            case '2': //余额不足
                $arrRet['cmd'] = "1";
                $arrRet['msg'] = "您的余额不足!";
                break;
            case '3': //核对投注额失败
                $arrRet['cmd'] = "1";
                $arrRet['msg'] = "您的实际投注额核对失败!";
                break;
            case '4': //已开奖过了
                $arrRet['cmd'] = "1";
                $arrRet['msg'] = "本期已开奖过了!";
                break;
            case '5': //投注额低于最小限制
                $arrRet['cmd'] = "1";
                $arrRet['msg'] = $arr[0]["msg"];
                break;
            case '6': //投注额大于限制
                $arrRet['cmd'] = "1";
                $arrRet['msg'] = $arr[0]["msg"];
                break;
            case '99': //数据库错误
                $arrRet['cmd'] = "1";
                $arrRet['msg'] = "系统错误，投注失败，请稍后再试!";
                break;
            default:
                $arrRet['cmd'] = "1";
                $arrRet['msg'] = "未知错误!";
                break;
        }

        return $this->result($arrRet['cmd'],$arrRet['msg']);
    }

    function GetTableContent($act,$page,$pagesize,$arrnoinfo)
    {
        $tablegame = $this->GetGameTableName($act,"game");
        $tablegametz = $this->GetGameTableName($act,"users_tz");
        $tablegamekg = $this->GetGameTableName($act,"kg_users_tz");
        $MinuteAdd = 15; //北京数据源
        if(in_array($act,array(0,1,2,15))) {
            $MinuteAdd = "3";
        }elseif(in_array($act,array(8,9,10,13))){//加拿大源
            $MinuteAdd = "13";
        }elseif(in_array($act,array(18,19,20,21))) {//韩国源
            $MinuteAdd = "5";
        }
         $sql="select t.id,t.kgtime,now() as nowtime,t.kj,t.kgjg,ifnull(tz.points,0) as points,ifnull(tz.hdpoints,0) as hdpoints from {$tablegame} as t left join {$tablegametz} tz on tz.NO=t.id and tz.uid={$_SESSION[usersid]}  where t.kgtime < DATE_ADD(NOW(),INTERVAL {$MinuteAdd} MINUTE) order by id desc limit 6";
        $list=db::get_all($sql,'assoc');
        $result=[];
        foreach ($list as $k=>$v){
            $result[$k]['id']=$v['id'];
            $result[$k]['kj']=$v['kj'];
            $t=strtotime($v['kgtime'])-strtotime($v['nowtime']);
            $result[$k]['stoptime'] = $t - $arrnoinfo['game_tz_close'];
            $result[$k]['kjtime']=$t + $arrnoinfo['game_kj_delay'];//-$result[$k]['stoptime'];
            $arrTmpKg=explode('|', $v['kgjg']);//开奖结果
            if(count($arrTmpKg)==4) {
                $result[$k]['num'] = $arrTmpKg[3];
                $result[$k]['num2'] = $arrTmpKg[2];
                $result[$k]['num1'] = $arrTmpKg[1];
                $result[$k]['num0'] = $arrTmpKg[0];
            }else{
                $result[$k]['num']='';
            }
            $result[$k]['kgtime']=date('H:i:s',strtotime($v['kgtime']));
            if($v['kj'] == 0)
            {
                if( (($arrnoinfo['prekgtime']) <= $arrnoinfo['game_tz_close']) && $v['id'] == $arrnoinfo['preno'] ) //正在开奖
                {
                    $result[$k]['status']=3;//
                }                else                {

                    if($this->DateDiff($v["kgtime"],$v["nowtime"],"s") > 0)
                    {
                        $result[$k]['status']=2;//投注
                    }                    else                    {

                        $result[$k]['status']=3;
                    }
                }
                $TmpKaiNum = "";
            }            else            {
                $result[$k]['status']=1;//已开奖
                /*if($act == "0" || $act == "1" || $act == "2" || $act == "3" || $act == "4" || $act == "5" ||
                    $act == "8" || $act == "9" || $act == "10" || $act == "11" || $act == "12" || $act == "13" ||
                    $act == "18" || $act == "19" || $act == "20" || $act == "21"
                ) //快乐8类
                {
                    $kjNumberStr = ($arrTmpKg[2] == "-1") ? (show_num($arrTmpKg[0],1)."<i class='hja'></i>".show_num($arrTmpKg[1],1) ) : ( show_num($arrTmpKg[0],1)."<i class='hja'></i>".show_num($arrTmpKg[1],1)."<i class='hja'></i>".show_num($arrTmpKg[2],1)  );
                    $kjFinal = $arrTmpKg[3];
                    //$value_kj=" = <em class='finals final'><i>{$kjFinal}</i></em>";
                    $value_kj="<i class='hdeng'></i>".show_num($arrTmpKg[3],3);
                    if($act == "11" || $act == "12" || $act == "13" || $act == "21") //36游戏
                    {
                        switch($arrTmpKg[3])
                        {
                            case 1:
                                $kjFinal = "豹";
                                $value_kj="<i class='hdeng'></i>".show_num(1,2);
                                break;
                            case 2:
                                $kjFinal = "对";
                                $value_kj="<i class='hdeng'></i>".show_num(2,2);
                                break;
                            case 3:
                                $kjFinal = "顺";
                                $value_kj="<i class='hdeng'></i>".show_num(3,2);
                                break;
                            case 4:
                                $kjFinal = "半";
                                $value_kj="<i class='hdeng'></i>".show_num(4,2);
                                break;
                            case 5:
                                $kjFinal = "杂";
                                $value_kj="<i class='hdeng'></i>".show_num(5,2);
                                break;
                            default:
                                $kjFinal = "";
                                break;
                        }
                    }
                    //$TmpKaiNum = "{$kjNumberStr} = <em class='finals final'><i>{$kjFinal}</i></em>";
                    $TmpKaiNum = "{$kjNumberStr}{$value_kj}";
                }
                else if($act == "6" || $act == "7" || $act == "14" || $act == "15" || $act == "16" || $act == "17") //pk类，PK10、PK冠军、PK22、急速10、PK龙虎、PK冠亚军
                {
                    //取得1-10个开奖结果排列
                    $arrKJResult = explode("|",$rs["kgNo"]);
                    $TmpKaiNum = "";
                    $kjNumPrefix = "";
                    for($i = 1; $i <= count($arrKJResult);$i++)
                    {
                        $kjNumPrefix = "light";
                        switch($act)
                        {
                            case "6": //pk10
                                $TmpSuffixNum = $arrTmpKg[0];

                                if($arrTmpKg[0] == 0)
                                    $TmpSuffixNum = 10;

                                if($i == $TmpSuffixNum)
                                    $kjNumPrefix = "regular";
                                break;
                            case "7": //pk冠军
                                if($i == 1)
                                    $kjNumPrefix = "regular";
                                break;
                            case "14": //pk22
                                if($i <= 3)
                                    $kjNumPrefix = "regular";
                                break;
                            case "15": //急速10
                                if($i == 1)
                                    $kjNumPrefix = "regular";
                                break;
                            case "16": //pk龙虎
                                if($i == 1 || $i == 10)
                                    $kjNumPrefix = "regular";
                                break;
                            case "17": //pk冠亚军
                                if($i == 1 || $i == 2)
                                    $kjNumPrefix = "regular";
                                break;
                            default:
                                break;
                        }
                        $theKjNumber = substr("0" . $arrKJResult[$i-1],-2);
                        $TmpKaiNum .= "<em class='{$kjNumPrefix}{$theKjNumber}'></em>";

                    }
                    //取得最后开奖结果
                    $LastKGResult = "<em class='final'><i>{$arrTmpKg[3]}</i></em>";
                    //$LastKGResult = show_num($arrTmpKg[3],3);
                    if($act == "16") //pk龙虎单独处理
                    {
                        if($arrTmpKg[3] == 1) //龙
                        {
                            //$LastKGResult = "<em class='final'><i>龙</i></em>";
                            $LastKGResult = "<i class='lh n1'></i>";
                        }
                        else //虎
                        {
                            //$LastKGResult = "<em class='final'><i>虎</i></em>";
                            $LastKGResult = "<i class='lh n2'></i>";
                        }
                    }
                    $TmpKaiNum .= $LastKGResult;
                }*/
            }
            $result[$k]['points']=$v['points'];
            $result[$k]['hdpoints']=$v['hdpoints'];

        }

        return array('list'=>$result);
    }
    function item(){
        $id=Req::get('id','intval');
        $No=Req::get('no','intval');
        $this->assign('no',$No);
        $tabletz = $this->GetGameTableName($id,'users_tz');
        $tablegame = $this->GetGameTableName($id,"game");
        if($tabletz == "")
            return "提交参数错误！";
        //取押注情况
        $sql = "SELECT tz.tznum,tz.tzpoints,tz.points,tz.hdpoints,tz.zjpoints,tz.zjpl,g.zjpl,g.kj,g.kgtime,g.kgjg FROM {$tabletz} tz right join {$tablegame} g on g.id=tz.NO and tz.uid = '{$_SESSION['usersid']}' WHERE g.id = '{$No}'";
        $result=db::get_one($sql,'assoc');
        if(is_array($result)){
            $arrtznum = explode("|",$result['tznum']);
            $arrtzpoints = explode("|",$result["tzpoints"]);
            $arrzjpoints = explode("|",$result['zjpoints']);
            $hdpoints = $result['hdpoints'];
            $points = $result['points'];
            $zjpl=$result['zjpl'];
            $arrRwardOdds = explode("|",$result['zjpl']);
            $kgtime = $result['kgtime'];
            $this->assign('arrtznum',$arrtznum);
            $this->assign('arrtzpl',explode("|",$result['zjpl']));
            if($result['kj']==1) {
                $kjjg = explode('|', $result['kgjg']);
                if($id==16){
                    if($kjjg[3] == 1){ //龙
                        $jg=$kjjg[0].' > '.$kjjg[1].' = 龙';
                    }else{ //虎
                        $jg=$kjjg[0].' > '.$kjjg[1].' = 虎';
                    }

                }elseif (in_array($id, array(15,6,7))) {
                    $jg = $kjjg[0];
                }elseif (in_array($id,array(2,10,17,20))){
                    $jg=$kjjg[0].' + '.$kjjg[1].' = '.$kjjg[3];
                }elseif (in_array($id,array(0,1,3,4,5,8,9,14,18,19))){
                    $jg=$kjjg[0].' + '.$kjjg[1].' + '.$kjjg[2].' = '.$kjjg[3];
                }elseif (in_array($id,array(11,12,13,21))){
                    switch($kjjg[3])
                    {
                        case 1:
                            $kjFinal = "豹";
                            break;
                        case 2:
                            $kjFinal = "对";
                            break;
                        case 3:
                            $kjFinal = "顺";
                            break;
                        case 4:
                            $kjFinal = "半";
                            break;
                        case 5:
                            $kjFinal = "杂";
                            break;
                        default:
                            $kjFinal = "";
                            break;
                    }
                    $jg=$kjjg[0].' + '.$kjjg[1].' + '.$kjjg[2].' = '.$kjFinal;
                }
            }else{
                $jg='未开奖';
            }
            $this->assign('jg',$jg);
        }else{
            return "<p>很抱歉,无投注记录！</p>";
        }
        //取标准赔率
        $reward_num_type = $this->GetGameOddsType($id);

        $sql = "SELECT GROUP_CONCAT(num SEPARATOR '|') AS strnum,GROUP_CONCAT(odds SEPARATOR '|') AS strodds FROM gameodds WHERE game_type = '{$reward_num_type}' ORDER BY num";
        $result=db::get_one($sql,'assoc');
        if(is_array($result)) {
            $arrStdNums = explode("|",$result['strnum']);
            $arrStdOdds = explode("|",$result['strodds']);
        }else{
            return "无法取得标准赔率";
        }
        $this->assign('Nums',$arrStdNums);
        $this->assign('Odds',$arrStdOdds);
        //重新格式化押注情况
        $arrNewtz = array();
        $arrNewhdPoints = array();
        foreach($arrStdNums as $num)
        {
            $arrNewtz[$num] = 0;
            $arrNewhdPoints[$num] = 0;
        }
        for($i = 0; $i < count($arrtznum); $i++)
        {
            $arrNewtz[$arrtznum[$i]] = $arrtzpoints[$i];
            $arrNewhdPoints[$arrtznum[$i]] = $arrzjpoints[$i];
        }

        $this->assign('arrNewhdPoints',$arrNewhdPoints);
        $this->assign('arrNewtz',$arrNewtz);
        $games=$this->GetGameConfig($id);
        $this->assign('game_name',$games['game_name']);
        //$info=$this->RefreshPoints();
        //$this->assign('money',$info);
        return $this->display('game_item');
    }

    function GetOdds($act,$No,$LastNo)
    {
        $tablegame = $this->GetGameTableName($act,"game");
        $tablegamekg = $this->GetGameTableName($act,"kg_users_tz");
        //号码表格
        //取赔率
        $sql = "select zjpl from {$tablegame} where id in({$No},{$LastNo}) order by id";
        $list=db::get_all('select tzpoints,zjpl from '.$tablegame.' where id in('.$No.','.$LastNo.')','assoc');
        if(is_array($list)) {
            $curOdds = $list[1]['zjpl'];
            $lastOdds = $list[0]['zjpl'];
        }
        $currPoint=$list[1]['tzpoints'];
        $arrCurOdds = explode('|',$curOdds);
        $arrLastOdds = explode('|',$lastOdds);
        //WriteLog($curOdds);
        //取已投注
        $arrHadPress = array();
        $step = $this->GetFromBeginNumStep($act);
        for($i = 0; $i < count($arrCurOdds); $i++){
            $arrHadPress[] = 0;
        }
        $sql='select tznum,tzpoints from '.$tablegamekg.' where NO='.$No.' and uid='.$_SESSION['usersid'];
        $list=db::get_all($sql,'assoc');
        foreach ($list as $k=>$v){
            $arrHadPress[$v['tznum']-$step] = $v['tzpoints'];
        }
        if($act==16){
            $in='n';
        }elseif(in_array($act,[11,12,13,21])){
            $in='3';
        }
        return array('currOdds'=>$arrCurOdds,'currPoint'=>$currPoint,'press'=>$arrHadPress,'step'=>$step,'in'=>$in);
    }

    /*
        *
        */
    function CheckPressStrValid($gametype,$press)
    {
        $ret = false;
        $sql = "select reward_num from game_config where game_type = '{$gametype}'";
        $result=db::get_one($sql);
        $pressCount = count($press) - 1;
        if($pressCount == $result->reward_num) {
            $ret = true;
        }
        return $ret;
    }
    /* 检测是否设置了自动投注
    *
    */
    function CheckAutoPress($t)
    {
        $tableName =$this->GetGameTableName($t,"auto");
        $sql = "select 1 from " . $tableName . " where uid = '{$_SESSION['usersid']}'";
        $result=db::get_one($sql);
        if($result) {
            return true;
        }else {
            return false;
        }
    }

    /* 检测本期投注时间是否已过
    *
    */
    function CheckGameTimeout($t,$no)
    {
        $tableName = $this->GetGameTableName($t,"game");
        $retState = true;
        $sql = "select game_kj_delay,game_tz_close from game_config where game_type = '{$t}'";
        $result=db::get_one($sql,'assoc');
        if(is_array($result))
        {
            $game_kj_delay = $result["game_kj_delay"];
            $game_tz_close = $result["game_tz_close"];
        }
        $sql = "select kj,kgtime,now() as servertime from " . $tableName . " where id = '{$no}'";
        $result=db::get_one($sql,'assoc');
        if(is_array($result))
        {
            if($result["kj"] == 0 && $this->DateDiff($result["kgtime"],$result["servertime"],"s") - $game_tz_close > 0)
                $retState = false;
        }
        return $retState;
    }

    function auto(){
        if(IS_AJAX){
            $act=Req::post('act');
            if($act=='saveautomodel'){
                return $this->SaveAutoModel();
            }elseif ($act=='changautomodel') {
                return $this->ajax_auto();
            }elseif ($act='removeautomodel'){
                return $this->RemoveAutoModel();
            }
        }
        $id=Req::get('id','intval');
        $this->assign('act',$id);
        $tableautotz = $this->GetGameTableName($id,"auto_tz");
        $tableauto = $this->GetGameTableName($id,"auto");
        //取当前自动下注配置
        $sql = "SELECT autoid,startNO,endNO,minG,maxG,start_auto_id FROM {$tableauto} WHERE uid = '{$_SESSION['usersid']}'";                 $curr=db::get_one($sql);
        if(!$curr->autoid) {
            $curr=(object)[];
            //最新开奖号码
            $new_no = $this->GetNewNo($id);
            $curr->num=3000;
            $curr->startNO=$new_no;
            $curr->minG=3000;
            $curr->maxG=999999999;
        }else{
            
            $curr->num=$curr->endNO-$curr->startNO;
        }
        $this->assign('curr',$curr);

        //模式列表
        $sql = "SELECT id,tzname,tzpoints,tzid,winid,lossid FROM {$tableautotz} WHERE uid = '{$_SESSION['usersid']}'";
        $list=db::get_all($sql);
        foreach ($list as $k=>$v){
            $list[$k]->tzpoints=number_format($v->tzpoints);
        }
        $this->assign('list',$list);
        $this->display('game_auto');
    }
    private function ajax_auto(){
        $GameType = intval($_POST["gtype"]);
        $WinOrLossID = intval($_POST['v']);
        $RecID = intval($_POST['cid']);
        $WinOrLossType = Req::post('ct');
        $tableautotz = $this->GetGameTableName($GameType,"auto_tz");
        $sql = "update {$tableautotz} set " . (($WinOrLossType == "win") ? "winid" : "lossid") . " = {$WinOrLossID} where id = {$RecID} and uid = '{$_SESSION['usersid']}'";
        $result = db::_query($sql);
        return $this->result(0,'修改成功');
    }/* 保存自动投注模式
	*
	*/
    private function SaveAutoModel()
    {
        $GameType = intval($_POST["gtype"]);
        $CurNo = intval($_POST['no']);
        $BeginNo = intval($_POST["bno"]);
        $tzCount = intval($_POST["cnt"]);
        $tzMaxG = intval($_POST["maxg"]);
        $tzMinG = intval($_POST["ming"]);
        $BeginRecID = intval($_POST["cid"]);

        $arrRet = array('cmd'=>'ok','msg'=>'');

        if($BeginNo < $CurNo){
            return $this->result(1,'开始期号至少要大于当前的期号!');
        }
        if($tzCount < 10)
        {
            return $this->result(1,'投注期数至少不少于10期!');
        }
        if($tzMinG  < 100)
        {
            return $this->result(1,'宝币下限至少不少于100');
        }
        if($tzMinG >= $tzMaxG)
        {
            return $this->result(1,'宝币下限必须要小于上限！');
        }

        $tableautotz = $this->GetGameTableName($GameType,"auto_tz");
        $sql = "select count(id) cnt from {$tableautotz} where id = {$BeginRecID} and uid = '{$_SESSION['usersid']}'";
        $rs = db::get_one($sql);
        if($rs->cnt < 1)
        {
            return $this->result(1,'您所要选择开始的投注模式已不存在，请刷新页面!');
        }
        if($tzMaxG < $_SESSION['points']){
            return $this->result(1,'您当前的宝币已经大于自动投注设置的上限了，您可以加大上限或者把一部分宝币转回银行!');
        }

        $table_kg_users_tz = $this->GetGameTableName($GameType,"kg_users_tz");
        $sql = "select max(NO) as maxno from {$table_kg_users_tz} where uid = '{$_SESSION['usersid']}'";
        $rs = db::get_one($sql,'assoc');
        $BeginNo = ($BeginNo > $rs['maxno']) ? $BeginNo : ($rs['maxno']+1);
        $endNo = $BeginNo + $tzCount;
        $tableauto = $this->GetGameTableName($GameType,"auto");
        $sql = "insert into {$tableauto}(startNO,endNO,minG,maxG,autoid,usertype,status,uid,start_auto_id)
				values({$BeginNo},{$endNo},{$tzMinG},{$tzMaxG},{$BeginRecID},0,1,{$_SESSION['usersid']},'{$BeginRecID}')";
        if(db::_query($sql,false)){
            return $this->result(0,'保存成功，系统将从第'.$BeginNo.'期开始为您自动投注(注意:您不在线也会自动投注)');
        }else{
            return $this->result(1,'系统繁忙，保存失败!');
        }
    }

    /* 取消自动投注
    *
    */
    private function RemoveAutoModel()
    {
        $GameType = intval($_POST["gtype"]);
        $tableauto = $this->GetGameTableName($GameType,"auto");
        $arrRet = array('cmd'=>'ok','msg'=>'');

        $sql = "delete from {$tableauto} where uid = '{$_SESSION['usersid']}'";
        if(db::_query($sql,false) > 0)
        {
            return $this->result(0,'ok');
        }
        else
        {
            return $this->result(1,'err');
        }
    }

    /* 修改自动投注模式
    *
    */
    private function ChangeAutoModel()
    {
        global $db;
        $GameType = intval($_POST["gtype"]);
        $WinOrLossID = intval($_POST['v']);
        $RecID = intval($_POST['cid']);
        $WinOrLossType = str_check($_POST['ct']);
        $tableautotz = GetGameTableName($GameType,"auto_tz");
        $arrRet = array('cmd'=>'ok','msg'=>'');

        $sql = "update {$tableautotz} set " . (($WinOrLossType == "win") ? "winid" : "lossid") . " = {$WinOrLossID} where id = {$RecID} and uid = '{$_SESSION['usersid']}'";
        //WriteLog($sql);
        $result = $db->query($sql);
        $arrRet['cmd'] = "ok";
        $arrRet['msg'] = "修改成功";
        echo json_encode($arrRet);
        exit;
    }

    /* 保存模式
    *
    */
    private function SaveModel()
    {
        global $db;
        $GameType = intval($_POST["gtype"]);
        $ID = intval($_POST["thev"]);
        $newName = ChangeEncodeU2G(str_check($_POST["thename"]));
        $newName = substr($newName,0,20);
        $press = str_check($_POST["press"]);
        $totalScore = intval($_POST["total"]);
        $tableautotz = GetGameTableName($GameType,"auto_tz");
        $tableauto = GetGameTableName($GameType,"auto");
        $arrRet = array('cmd'=>'ok','msg'=>'');

        //判断投注串合法性
        if(!CheckPressStrValid($GameType,$press))
        {
            $arrRet['cmd'] = "err";
            $arrRet['msg'] = "投注验证失败!";
            echo json_encode($arrRet);
            exit;
        }
        //检查是否正在自动投注
        if(CheckAutoPress($GameType))
        {
            $arrRet['cmd'] = "err";
            $arrRet['msg'] = "您当前已设置了自动投注，不允许编辑模式，请先取消自动投注!";
            echo json_encode($arrRet);
            exit;
        }
        //名称是否重名
        $sql = "select count(*) cnt from {$tableautotz} where id <> {$ID} and tzname = '{$newName}' and uid = '{$_SESSION['usersid']}'";
        $result = $db->query($sql);
        $rs = $db->fetch_array($result);
        if($rs["cnt"] > 0)
        {
            $arrRet['cmd'] = "err";
            $arrRet['msg'] = "模式名称重名了，请先修改!";
            echo json_encode($arrRet);
            exit;
        }
        $step = GetFromBeginNumStep($GameType);

        $arrPress = explode(",",$press);
        $PressStr = "";
        $sumScore = 0;
        for($i = 0 ; $i < count($arrPress); $i++)
        {
            if($arrPress[$i] != "" && intval($arrPress[$i]) > 0)
            {
                $PressStr .= ($i+$step) . "," . $arrPress[$i] . "|";
                $sumScore += intval($arrPress[$i]);
            }
        }
        if($PressStr == "")
        {
            $arrRet['cmd'] = "err";
            $arrRet['msg'] = "您还没有选择投注!";
            echo json_encode($arrRet);
            exit;
        }
        $PressStr = substr($PressStr,0,-1);
        if($sumScore != $totalScore)
        {
            $arrRet['cmd'] = "err";
            $arrRet['msg'] = "您的投注信息验证错误!";
            echo json_encode($arrRet);
            exit;
        }
        $sql = "select game_press_min,game_press_max from game_config where game_type = '{$GameType}'";
        $result = $db->query($sql);
        if($rs = $db->fetch_array($result))
        {
            $press_min = $rs['game_press_min'];
            $press_max = $rs['game_press_max'];
            if($sumScore < $press_min)
            {
                $arrRet['cmd'] = "err";
                $arrRet['msg'] = "投注额至少大于下限" . $press_min;
                echo json_encode($arrRet);
                exit;
            }
            if($sumScore > $press_max)
            {
                $arrRet['cmd'] = "err";
                $arrRet['msg'] = "投注额不能超过上限" . $press_max;
                echo json_encode($arrRet);
                exit;
            }
        }
        if($ID == "0")
            $sql = "insert into {$tableautotz}(uid,tzname,tzpoints,tznum,tzid,winid,lossid)
						values({$_SESSION['usersid']},'{$newName}',{$totalScore},'{$PressStr}',0,0,0)";
        else
            $sql = "update {$tableautotz} set tzname = '{$newName}',tzpoints={$totalScore},tznum='{$PressStr}'
					where id = '{$ID}' and uid = '{$_SESSION['usersid']}'";
        $result = $db->query($sql);
        $autoID = 0;
        if($ID == "0")
        {
            $insertID = $db->insert_id();
            $autoID = $insertID;
            if($insertID > 0)
                $sql = "update {$tableautotz} set winid={$insertID},lossid = {$insertID} where id = {$insertID} and uid='{$_SESSION['usersid']}'";
            $result = $db->query($sql);
        }

        if($ID != '0') $autoID = $ID;
        //更新模式
        $sql = "select EditPressModel({$GameType},{$autoID},{$_SESSION['usersid']},'{$PressStr}')";
        $result = $db->query($sql);

        $arrRet['cmd'] = "ok";
        $arrRet['msg'] = "";
        echo json_encode($arrRet);
        exit;
    }

    /*删除模式
    *
    */
    private function RemoveUserModel()
    {
        global $db;
        $GameType = intval($_POST["gtype"]);
        $ID = intval($_POST["id"]);
        $tableautotz = GetGameTableName($GameType,"auto_tz");
        $arrRet = array('cmd'=>'ok','msg'=>'');
        //检查是否正在自动投注
        if(CheckAutoPress($GameType))
        {
            $arrRet['cmd'] = "err";
            $arrRet['msg'] = "您当前已设置了自动投注，不允许编辑模式，请先取消自动投注!";
            echo json_encode($arrRet);
            exit;
        }
        $sql = "delete from {$tableautotz} where id = {$ID} and uid = '{$_SESSION['usersid']}'";
        $result = $db->query($sql);
        //删除模式
        $sql = "delete from gameall_auto_tz where autoid = {$ID} and uid = '{$_SESSION['usersid']}' and gametype='{$GameType}'";
        $result = $db->query($sql);

        $arrRet['cmd'] = "ok";
        $arrRet['msg'] = "删除成功!";
        echo json_encode($arrRet);
        exit;
    }
    /* 检测是否可以去投注
    *
    */
    function CheckPress()
    {
        global $db;
        $GameType = intval($_POST["gtype"]);
        $No = intval($_POST["no"]);
        $tableName = GetGameTableName($GameType,"auto");
        $arrRet = array('cmd'=>'ok','msg'=>'');
        if($tableName == "")
        {
            $arrRet['cmd'] = "err";
            $arrRet['msg'] = "游戏类型错误!";
            echo json_encode($arrRet);
            exit;
        }
        //判断总游戏是否允许下注
        $sql = "select fldVar,fldValue from sys_config where fldVar in('game_open_flag','game_shutdown_reason') order by fldIdx";
        $result = $db->query($sql);
        if($rs = $db->fetch_array($result))
        {
            if($rs["fldValue"] == "1")
            {
                $rs = $db->fetch_array($result);
                $arrRet['cmd'] = "showdown";
                $arrRet['msg'] = "游戏已停止下注,原因:" . ChangeEncodeG2U($rs["fldValue"]);
                echo json_encode($arrRet);
                exit;
            }

        }
        //判断单个游戏是否允许下注
        $sql = "select isstop,stop_msg from game_config where game_type = '{$GameType}'";
        $result = $db->query($sql);
        if($rs = $db->fetch_array($result))
        {
            if($rs["isstop"] == 1)
            {
                $arrRet['cmd'] = "showdown";
                $arrRet['msg'] = "游戏已停止下注,原因:" . ChangeEncodeG2U($rs["stop_msg"]);
                echo json_encode($arrRet);
                exit;
            }

        }
        $sql = "select 1 from " . $tableName . " where uid = '{$_SESSION['usersid']}'";
        $result = $db->query($sql);
        if($rs = $db->fetch_array($result))
        {
            $arrRet['cmd'] = "auto";
            $arrRet['msg'] = "您已设置了自动投注，请先停止!";
        }
        //WriteLog(json_encode($arrRet));
        echo json_encode($arrRet);
        exit;
    }
    function record(){
        $page = isset($_GET['page'])?$_GET['page']:1;
        $page =intval($page);
        $act=Req::get('id','intval');
        $this->assign('id',$act);
        $pagesize = 20;
        $tableuserstz = $this->GetGameTableName($act,"users_tz");
        $tablegame = $this->GetGameTableName($act,"game");
        //号码表格
        //$sql = "SELECT count(id) FROM {$tableuserstz} WHERE uid = {$_SESSION['usersid']} and `time` > DATE_ADD(CURDATE(),INTERVAL -6 DAY)";
        //$TotalRecCount = $db->GetRecordCount($sql);
        $sql = "
		 	SELECT a.id,a.no,DATE_FORMAT(a.time,'%H:%i:%s') as time,a.points,a.hdpoints
			FROM {$tableuserstz} a 
			
			WHERE a.uid = {$_SESSION['usersid']} AND a.`time` > DATE_ADD(CURDATE(),INTERVAL -1 DAY) 
			ORDER BY a.id desc limit 60";
        $list=db::get_all($sql);
        foreach ($list as $k=>$v){
            $list[$k]->hd=($v->hdpoints-$v->points);
            /*$list[$k]->hd=sprintf('%.2f',($v->hdpoints-$v->points)/1000);
            $list[$k]->points=sprintf('%.2f',$v->points/1000);
            $list[$k]->hdpoints=sprintf('%.2f',$v->hdpoints/1000);*/
        }
        $this->assign('list',$list);
        $games=$this->GetGameConfig($act);
        $this->assign('game_name',$games['game_name']);
        $this->display('game_record');
    }
    function total(){
        $page = isset($_GET['page'])?$_GET['page']:1;
        $page =intval($page);
        $act=Req::get('id','intval');
        $this->assign('id',$act);
        $pagesize = 20;
        $tableuserstz = $this->GetGameTableName($act,"users_tz");
        $tablegame = $this->GetGameTableName($act,"game");
        //号码表格
        //$sql = "SELECT count(id) FROM {$tableuserstz} WHERE uid = {$_SESSION['usersid']} and `time` > DATE_ADD(CURDATE(),INTERVAL -6 DAY)";
        //$TotalRecCount = $db->GetRecordCount($sql);
        $sql = "
		 	SELECT a.id,a.no,a.points,a.hdpoints
			FROM {$tableuserstz} a 
			WHERE a.uid = {$_SESSION['usersid']} AND a.`time` > DATE_ADD(CURDATE(),INTERVAL -1 DAY)  and a.hdpoints>0
			ORDER BY a.id desc limit 60";
        $list=db::get_all($sql);

        $this->assign('list',$list);
        $games=$this->GetGameConfig($act);
        $this->assign('game_name',$games['game_name']);
        $this->display('game_total');
    }
    function rule(){
        $this->display('game_rule');
    }
    //取离第一个开奖数字步长
    function GetFromBeginNumStep($GameType)
    {
        $step = 0;
        if($GameType == "14")
            $step = 6;
        else if($GameType == "1" || $GameType == "5" || $GameType == "9" || $GameType == "17" || $GameType == "19")
            $step = 3;
        else if($GameType == "2" || $GameType == "10" || $GameType == "20")
            $step = 2;
        else if($GameType == "6" || $GameType == "7" || $GameType == "11" || $GameType == "12" || $GameType == "13" || $GameType == "15" || $GameType == "16" || $GameType == "21")
            $step = 1;

        return $step;
    }
    /* 取上盘押注情况
	*
	*/
    function getLastPress(){
        $GameType = Req::post('gtype','intval');
        $No = Req::post('no','intval');
        $tabletz = $this->GetGameTableName($GameType,"users_tz");
        $tablekg = $this->GetGameTableName($GameType,"kg_users_tz");
        $arrRet = array('cmd'=>'','msg'=>'');

        if($tabletz == ""){
            return $this->result(1,"游戏类型错误!");
        }
        $pos = $this->GetFromBeginNumStep($GameType);
        $pos = -$pos;
        $retMsg = "";
        $sql = "select tznum,tzpoints from {$tabletz} where  uid = '{$_SESSION['usersid']}' order by id desc";
        $rs = db::get_one($sql,'assoc');
        if($rs){
            $arrNum = explode("|",$rs['tznum']);
            $arrPoints = explode("|",$rs['tzpoints']);

            for($i = 0; $i < count($arrNum); $i++)
            {
                $retMsg .= ($arrNum[$i] + $pos) . "," . $arrPoints[$i] . "|";
            }
            if($retMsg != "")
            {
                $retMsg = substr($retMsg,0,-1);
            }
        }else{
            $sql = "select tznum,tzpoints from {$tablekg} where uid = '{$_SESSION['usersid']}' order by id desc";
            $result = db::_query($sql);
            while($rs = db::_assoc($result))
            {
                $retMsg .= ($rs['tznum'] + $pos) . "," . $rs['tzpoints'] . "|";
            }
            if($retMsg != "")
            {
                $retMsg = substr($retMsg,0,-1);
            }
        }
        if($retMsg == "")
        {
            return $this->result(1,'您上期没有投注!');
        }else{
            return $this->result(0,$retMsg);
        }
    }
}